import React, {PureComponent, Fragment} from 'react';
import moment from 'moment';
import {connect} from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select, TreeSelect, Popover, Tooltip,
} from 'antd';
import BuildModalTitle from '@/components/BuildModalTitle';

import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';


import debounce from 'lodash/debounce';
import {
  printUtils,
  renderTreeNodes,
  download,
  formateObjToParamStr,
  printUtilsLevel,
  afterCloseModal, myencrypt, getEW, formateObjToParamStr2
} from '@/utils/utils';
import Detail from './../Owner/Detail';
import ReactDataGrid from 'react-data-grid';
import gold from './../../images/gold.png';
import wechat from './../../images/wechat.png';
import jsyh from './../../images/jsyh.png';
import request from '@/utils/request';
import config from '../../config/config';
import find from 'lodash/find';
import PaperInvoicing from './PaperInvoicing'
import AddOrEditForm from './addOrEditForm'
import {routerRedux} from "dva/router";
import AddOrEditStaffs from "@/pages/StoreHouseManagement/addOrEditUser";
import AreaMap from "@/components/AreaMap";

const FormItem = Form.Item;
const {confirm} = Modal;
const Option = Select.Option;
const InputGroup = Input.Group;

@connect(({invoicings_manage, loading, global}) => ({
  invoicings_manage,
  global,
  loading: loading.models.invoicings_manage,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      data: [],
      remark: '',
      invoicingData: []
    };
  }


  componentDidMount() {

    const {dispatch} = this.props;
    const {
      invoicings_manage: {pageLoaded, scrollData},
    } = this.props;

    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        invoicings_manage: {searchParams},
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'invoicings_manage/fetch',
        payload: searchParams,
        callback: () => {
          const {dispatch} = this.props;
          dispatch({
            type: 'invoicings_manage/changeLoaded',
          });
          dispatch({
            type: 'invoicings_manage/changeTableY',
          });
        },
      });

    }
    const that = this;
    request(`/all_regions`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          data: response.data.data,
        });
      }
    });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
    // document.addEventListener('keyup', this.keyupFunc);

  }

  keyupFunc = (e) => {
    if (e.keyCode === 13) {
      this.searchFunc();
    }
  };
  searchFunc = () => {
    const that = this;
    const {form, invoicings_manage: {searchParams}} = that.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      this.handleSearch({
        page: 1,
        per_page: searchParams.per_page,
        ...fieldsValue,
        start_date: fieldsValue.start_date ? moment(fieldsValue.start_date).format('YYYY-MM-DD') : '',
        end_date: fieldsValue.end_date ? moment(fieldsValue.end_date).format('YYYY-MM-DD') : '',
        region_id: fieldsValue.region_id ? fieldsValue.region_id.split('$')[0] : '',
        region_name: fieldsValue.region_id ? fieldsValue.region_id.split('$')[1] : '',

      });

    });
  };
  scroll = (e) => {
    console.log('scroll');
    const {dispatch} = this.props;
    dispatch({
      type: 'invoicings_manage/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const {dispatch} = this.props;

    // this.changeTableY();
    dispatch({
      type: 'invoicings_manage/changeTableY',
    });
  };
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    // document.removeEventListener('keyup', this.keyupFunc);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  findChildFunc = (cb) => {
    this.findChildLocation = cb;
  };
  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const {dispatch} = this.props;
    const {
      invoicings_manage: {searchInputType, searchInputText},
    } = this.props;
    dispatch({
      type: 'invoicings_manage/fetch',
      payload: {
        ...values,
        [searchInputType]: searchInputText,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const data = this.state.data;
    const {dispatch} = this.props;
    const {
      invoicings_manage: {searchParams, searchInputType, searchInputText},
    } = this.props;
    const form=this.props.form
    const getFieldDecorator=form.getFieldDecorator
    return (
      <Form layout="inline" className="search-form">
        <AreaMap form={form} searchParams={searchParams} getFieldDecorator={getFieldDecorator}/>
        <FormItem label="日期类型">
          {getFieldDecorator('date_type', {
            initialValue: searchParams.date_type,
          })(
            <Select style={{width: '100px'}}>
              {
                [{id: 'generation_date', value: '创建日期'}, {id: 'invoicing_date', value: '开票日期'}
                ].map((item, index) => {
                  return <Option key={index} value={item.id}>{item.value}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem label={'开始日期'}>
          {getFieldDecorator('start_date', {
            initialValue: searchParams.start_date ? moment(searchParams.start_date) : '',
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={true}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem label={'结束日期'}>
          {getFieldDecorator('end_date', {
            initialValue: searchParams.end_date ? moment(searchParams.end_date) : '',
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={true}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem label="开票类型">
          {getFieldDecorator('invoicing_type', {
            initialValue: searchParams.invoicing_type,
          })(
            <Select style={{width: '80px'}}>
              {
                [{id: '', value: '全部'}, {id: '6', value: '数电普票'}, {id: '7', value: '数电专票'}, {id: '1', value: '电子发票'}, {id: '2', value: '纸质普票'}, {id: '4', value: '纸质专票'}
                ].map((item, index) => {
                  return <Option key={index} value={item.id}>{item.value}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem label="开票来源">
          {getFieldDecorator('source', {
            initialValue: searchParams.source,
          })(
            <Select style={{width: '100px'}}>
              {
                [{id: '', value: '全部'}, {id: '1', value: '公众号开票'}, {id: '2', value: '柜台开票'}
                ].map((item, index) => {
                  return <Option key={index} value={item.id}>{item.value}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem label="发票状态">
          {getFieldDecorator('invoicing_statuses', {
            initialValue: searchParams.invoicing_statuses,
          })(
            <Select style={{width: '80px'}}>
              {
                [{id: '', value: '全部'}, {id: '-5', value: '已冲红'}, {id: '-4', value: '已作废'}, {id: '-3', value: '开票失败'},
                  {id: '1', value: '正在开票'}, {id: '2', value: '已开票'}
                ].map((item, index) => {
                  return <Option key={index} value={item.id}>{item.value}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem label="收费性质">
          {getFieldDecorator('modes', {
            initialValue: searchParams.modes,
          })(
            <Select style={{width: '80px'}}>
              {
                [{id: '', value: '全部'}, {id: '1', value: '一般水费'}, {id: '2', value: '卡表收费'},
                  {id: '3', value: '处罚收费'}, {id: '4', value: '水车收费'}, {id: '5', value: '补交水费'}, {id: '6', value: '预交收费'}
                ].map((item, index) => {
                  return <Option key={index} value={item.id}>{item.value}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem>
          <InputGroup compact>
            <Select onChange={(e) => {
              dispatch({
                type: 'invoicings_manage/changeOneProperty',
                payload: {
                  searchInputType: e,
                },
              });
            }} style={{width: '120px', color: '#000'}} value={searchInputType}>
              <Option value="order_number">发票订单号</Option>
              <Option value="invoice_code">发票代码</Option>
              <Option value="invoice_number">发票编号</Option>
              <Option value="associated_order_number">关联订单号</Option>
              <Option value="buyer_name">购方名称</Option>
              <Option value="clerk">开票人</Option>
            </Select>
            <Input style={{width: '130px'}} value={searchInputText} onKeyPress={this.keyPress} onChange={(e) => {
              dispatch({
                type: 'invoicings_manage/changeOneProperty',
                payload: {
                  searchInputText: e.target.value,
                },
              });
            }}/>
          </InputGroup>
        </FormItem>
        {/* <FormItem label="操作员">
          {getFieldDecorator('operator_name', {
            initialValue: searchParams.operator_name,
          })(<Input style={{ width: '110px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem label="户主姓名">
          {getFieldDecorator('name', {
            initialValue: searchParams.name,
          })(<Input style={{ width: '120px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem label="户主手机">
          {getFieldDecorator('mobile', {
            initialValue: searchParams.mobile,
          })(<Input style={{ width: '120px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem label="水表号">
          {getFieldDecorator('meter_number', {
            initialValue: searchParams.meter_number,
          })(<Input style={{ width: '110px' }} placeholder="请输入"/>)}
        </FormItem>*/}
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              this.searchFunc();
            }}
          >
            查询
          </Button>
          <Button style={{marginLeft: 8}} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }

  keyPress = (e) => {
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const {form} = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        this.searchFunc()
      });
    }
  }
  handleAdd = () => {
    const location = this.findChildLocation();
    console.log('location', location);
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'invoicings_manage/add',
      payload: {
        ...formValues,
        longitude: location[0],
        latitude: location[1],
      },
      callback() {
        message.success('添加压力传感器成功');
        that.setState({
          addModal: false,
        });
        const {
          invoicings_manage: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const {form} = this.props;
    const {dispatch} = this.props;
    const that = this
    form.resetFields();
    dispatch({
      type: 'invoicings_manage/changeOneProperty',
      payload: {
        searchInputType: 'order_number',
        searchInputText: '',
        searchParams: {
          company_ids:sessionStorage.getItem('company_sign'),
          company_id:'',
          start_date: moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', "YYYY-MM-DD").format("YYYY-MM-DD"),
          end_date: moment(new Date()).format('YYYY-MM-DD'),
          order_number: "",
          invoice_code: '',
          invoice_number: '',
          date_type: "generation_date",
          buyer_name: '',
          clerk: '',
          invoicing_type: '',
          invoicing_statuses: '',
          modes: '',
          source: '',
          mobile: '',
          page: 1,
          per_page: 50,
        },
      },
      callback() {
        that.handleSearch({
          company_ids:sessionStorage.getItem('company_sign'),
          company_id:'',
          start_date: moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', "YYYY-MM-DD").format("YYYY-MM-DD"),
          end_date: moment(new Date()).format('YYYY-MM-DD'),
          order_number: "",
          date_type: "generation_date",
          invoice_code: '',
          invoice_number: '',
          buyer_name: '',
          clerk: '',
          invoicing_type: '',
          invoicing_statuses: '',
          modes: '',
          source: '',
          mobile: '',
          page: 1,
          per_page: 50,
        });
      },
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    request(`/information_forms`, {
      method: 'POST',
      data:{
        order_number:this.state.editRecord.order_number,
        ...formValues,
      }
    }).then((response) => {
      if (response.status === 200) {
        console.log('申请红字专用发票信息表成功')
        message.success('申请红字专用发票信息表成功')
        that.setState({
          formsModal: false,
        });
        const {
          invoicings_manage: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  };
  print = (id) => {
    request(`/print/invoicings_manages/${id}`, {
      method: 'POST',
    }).then((response) => {
      if (response.status === 200) {
        if (response.data.data.account.price_nature.level === 3) {
          printUtilsLevel(response.data.data);
        } else {
          printUtils(response.data.data);
        }

      }

    });
  };
  handleExportinvoicings_manage = () => {
    const {
      invoicings_manage: {searchParams},
    } = this.props;
    console.log('searchParams', searchParams);
    download(`${config.prefix}/issued_invoice_files?Authorization=Bearer ${sessionStorage.getItem('token')}&order_direction=desc&${formateObjToParamStr2(({...searchParams,
      company_ids:getEW(searchParams.company_ids)}))}`);

  };
  Invoicing = () => {
    const state = this.InvoicingForm.state;
    const formValues = this.InvoicingForm.props.form.getFieldsValue();
    if(!formValues.company_id){
      message.error('请先选择公司')
      return
    }
    const that = this
    console.log('state', state)
    if (state.step === 1) {
      message.error('请选择发票类型')
      return
    }
    this.setState({
      loading: true,
    })
    confirm({
      title: '确定要开此发票吗',
      content: '请谨慎操作',
      centered: true,
      cancelText: '取消',
      okText: '确定',
      onOk() {
        if (!that.state.loading) {
          return false
        }
        let detail = [];
        for (let i = 0; i < state.invoices[0].detail.length; i++) {
          if (state.invoices[0].detail[i].goodsname) {
            if (!state.invoices[0].detail[i].item_total) {
              message.error(`第${i + 1}行金额不能为空`)
              return false
            }
            if (!state.invoices[0].detail[i].taxrate) {
              message.error(`第${i + 1}行税率不能为空`)
              return false
            }
            let item={
              goodsname: state.invoices[0].detail[i].goodsname,
              spec: state.invoices[0].detail[i].spec,
              hsbz: state.invoices[0].detail[i].hsbz ? 1 : 0,
              unit: state.invoices[0].detail[i].unit,
              num: Number(state.invoices[0].detail[i].num),
              price: state.invoices[0].detail[i].hsbz ? state.invoices[0].detail[i].price : state.invoices[0].detail[i].no_price,
              taxrate: Number(state.invoices[0].detail[i].taxrate), //税率
              // taxfreeamt: state.invoices[0].detail[i].hsbz ? //不含税金额
              //   Math.round((Number(state.invoices[0].detail[i].item_total) - Number(state.invoices[0].detail[i].itemTaxrate)) * 100) / 100
              //   :
              //   Number(state.invoices[0].detail[i].no_item_total),
              // taxamt: state.invoices[0].detail[i].hsbz ? //含税金额
              //   Number(state.invoices[0].detail[i].item_total)
              //   :
              //   Math.round((Number(state.invoices[0].detail[i].no_item_total) + Number(state.invoices[0].detail[i].itemTaxrate)) * 100) / 100,
              tax: Number(state.invoices[0].detail[i].itemTaxrate),//税额
              lslbs: Number(state.invoices[0].detail[i].taxrate) === 0 ? 1 : '',
              favouredPolicyFlag: Number(state.invoices[0].detail[i].taxrate) === 0 ? '' : '01',
              spbm:'110030101'
            }
            if(Number(state.invoices[0].detail[i].taxrate) === 0 ){
              item.yhzcbs=1;
              item.zzstsgl="免税";
            }
            console.log('item',item)
            detail.push(item)
          }
        }
        console.log("detail",detail)
        console.log("state",state)
        if (detail.length === 0) {
          message.error(`发票内容不能为空`)
          return false
        }

        request(`/custom_invoicings`, {
          method: 'POST',
          data: {
            mode: state.mode,
            buyer_name: state.mc,
            buyer_tax_number: state.nsrsbr,
            buyer_address: state.dzdh,
            buyer_bank_account: state.khh,
            invoice_push_mobile: state.sjhm,
            invoice_push_email: state.yxdz,
            invoicing_type: state.invoicing_type,
            remark: state.bz,
            company_id:formValues.company_id,
            detail: detail
          }
        }).then((response) => {
          if (response.status === 200) {
            message.success(`提交开"${state.mc}" 发票成功`)
            that.setState({
              loading: false,
              invoicingModal: false
            })
            const {
              invoicings_manage: {searchParams},
            } = that.props;
            that.handleSearch(searchParams);
          }
          setTimeout(function () {
            that.setState({
              loading: false
            })
          }, 5000)
        });
      },
      onCancel() {
        console.log('Cancel');
        that.setState({
          loading: false,
        })
      },
    });

  }
  handleClick = (key, row) => {
    console.log('key)', key);
    const {panes, routerMapping} = this.props.global;
    const {dispatch} = this.props;
    const activeKey = key;
    const that = this;
    if (find(panes, o => o.key == activeKey)) {
      console.log('已经存在');
    } else {
      panes.push({
        title: find(routerMapping, o => o.path == activeKey).name,
        content: 'New Tab Pane',
        key: activeKey,
      });
    }
    dispatch(routerRedux.push(activeKey));
    console.log('row.generation_date', row.generation_date)
    dispatch({
      type: 'global/changePanesAndActive',
      payload: {panes, activeKey},
      callback: function () {
        const sendSearchParams = {
          start_date: '',
          end_date: '',
          region_id: "",
          name: '',
          mobile: '',
          date_type: "generation_date",
          meter_number: '',
          operator_name: '',
          type: '',
          invoicing_status: '',
          page: 1,
          per_page: 50,
          id: row.payment_id,
        };
        console.log('sendSearchParams', sendSearchParams);
        dispatch({
          type: 'payment/changeLoadedFalse',
          callback: function () {
            dispatch({
              type: 'payment/changeSearchParams',
              payload: sendSearchParams,
            });
          }
        });

      }
    });
  };
  renderFormStatus=(information_form)=>{
    let status = ''
    switch (information_form.status) {
      case -1:
        status = <span >申请中</span>;
        break;
      case 1:
        status = <span>审核成功</span>;
        break;
      case 2:
        status =  <span style={{color: 'red'}}>审核失败</span>;
        break;
      case 3:
        status = <span style={{color: 'green'}}>申请成功</span>;
        break;
      case 4:
        status =   <span style={{color: 'red'}}>申请失败</span>;
        break;
      default:
        status = ''
        break
    }
    return status
  }
  popoverForm=(information_form)=>{

    return <div>
      <p>申请编号: <br/>{information_form.bill_number}</p>
      <p>信息表编号: <br/>{information_form.information_form_number}</p>
      <p>申请状态: <br/>{this.renderFormStatus(information_form)}</p>
      <p>生成时间: <br/>{information_form.generation_time}</p>
      <p>操作人: <br/>{information_form.clerk}</p>
      {information_form.pdf &&
        <p style={{color:"blue",cursor:'pointer'}}
        onClick={()=>{
          window.open(`${information_form.pdf}`);
        }
        }>查看PDF
        </p>
      }


    </div>
  }
  render() {
    const that = this;
    const {
      invoicings_manage: {data, loading, tableY, meta, searchParams, selectedRowKeys, summary},
      global: {gridTableW},
    } = this.props;
    const defaultColumnProperties = {
      resizable: true,
    };
    const username = sessionStorage.getItem('username')
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            invoicings_manage: {meta},
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '开票类型',
        width: 75,
        frozen: true,
        key: 'invoicing_type',
        formatter: (event) => {
          let text = '';
          switch (Number(event.value)) {
            case 1:
              return <span style={{
                padding: '1px 4px',
                fontSize: '12px',
                borderRadius: '1px',
                background: '#d4ddff',
                color: '#0055ff'
              }}>电子发票</span>;
            case 2:
              return <span style={{
                padding: '1px 4px',
                fontSize: '12px',
                borderRadius: '1px',
                background: '#c1ecff',
                color: '#0081c2'
              }}>纸质普票</span>;
            case 4:
              return <span style={{
                padding: '1px 4px',
                fontSize: '12px',
                borderRadius: '1px',
                background: '#fff0e3',
                color: '#dc9100'
              }}>纸质专票</span>;
            case 6:
              return <span style={{
                padding: '1px 4px',
                fontSize: '12px',
                borderRadius: '1px',
                background: '#c1ecff',
                color: '#0081c2'
              }}>数电普票</span>;
            case 7:
              return <span style={{
                padding: '1px 4px',
                fontSize: '12px',
                borderRadius: '1px',
                background: '#fff0e3',
                color: '#dc9100'
              }}>数电专票</span>;
            default:
              break;
          }
          return text;
        },
      },
      {
        name: '创建时间',
        width: 150,
        key: 'generation_time',
        frozen: true,
      },
      {
        name: '开票时间',
        width: 150,
        key: 'invoicing_time',
        frozen: true,
      },
      {
        name: '购方名称',
        width: 200,
        key: 'buyer_name',
        frozen: true,
      },
      {
        name: '开票金额',
        width: 100,
        key: 'amount',
        frozen: true,
        formatter: (event) => {
          return <div className={`money ${event.value < 0 ? 'error' : ''}`}><img className={'gold'} src={gold}
                                                                                 alt=""/>{event.value}</div>;
        },
      },
      {
        name: '开票状态',
        width: 80,
        key: 'invoicing_status',
        formatter: (event) => {
          let type = ''
          let text = '';
          switch (event.value) {
            case -5:
              text = '已冲红';
              return <span style={{color: 'red'}}>{type + text}</span>;
            case -4:
              text = '已作废';
              return <span style={{color: 'red'}}>{type + text}</span>;
            case -3:
              text = '开票失败';
              break;
            case -2:
              text = '不允许开票';
              break;
            case -1:
              text = '未开票';
              break;
            case 1:
              text = '正在开票';
              break;
            case 2:
              text = '已开票';
              break;
          }
          return <span title={type + text}>{type + text}</span>;
        },
      },
      {
        name: '发票代码/编号',
        width: 180,
        key: 'invoice_code',
        formatter: (event) => {
          return <span title={`${event.row.invoice_number}`}>
           {event.row.invoice_number}
            </span>;
        }
      },
      {
        name: '发票订单号',
        width: 170,
        key: 'order_number',
      },
      {
        name: '收费性质',
        width: 80,
        key: 'mode',
        formatter: (event) => {
          let text = '';
          switch (Number(event.value)) {
            case 1:
              if (find(that.permissions, {name: 'payment_record'})) {
                return <span style={{color: 'blue', cursor: 'pointer'}} onClick={() => {
                  this.handleClick('/payment', event.row)
                }}>一般水费</span>
              } else {
                return <span>一般水费</span>;
              }
            case 2:
              return <span>卡表收费</span>;
            case 3:
              return <span>处罚收费</span>;
            case 4:
              return <span>水车收费</span>;
            case 5:
              return <span>补交水费</span>;
            case 6:
              return <span>预交收费</span>;
            default:
              break;
          }
          return text;
        },
      },
      {
        name: '开票来源',
        width: 120,
        key: 'source',
        formatter: (event) => {
          let text = '';
          switch (Number(event.value)) {
            case 1:
              return <span><img style={{width: '20px', height: '20px', marginRight: '2px'}} src={wechat}
                                alt=""/>公众号缴费</span>;
            case 2:
              return <span>柜台开票</span>;
            default:
              break;
          }
          return text;
        },
      },
      {
        name: '开票标志',
        width: 80,
        key: 'invoicing_flag',
        formatter: (event) => {
          let text = '';
          switch (Number(event.value)) {
            case 1:
              return <span style={{color: 'blue'}}>蓝票</span>;
            case 2:
              return <span style={{color: 'red'}}>红票</span>;
            default:
              break;
          }
          return text;
        },
      },
      {
        name: '关联订单号',
        width: 100,
        key: 'associated_order_number',
      },
      {
        name: '开票员',
        width: 80,
        key: 'clerk',
      },
      {
        name:'红字专票信息表',
        width:160,
        key:'form',
        formatter:(event)=>{
          if(event.row.information_form.bill_number){
            return <div>
              <Popover title={'信息表'} content={this.popoverForm(event.row.information_form)}>
                <span style={{color:'blue',textDecoration:"underline"}}>
                  {this.renderFormStatus(event.row.information_form)}
                </span>
              </Popover>

                <Button
                  title={'刷新'}
                  size="small"
                  icon="reload"
                  shape="circle"
                  onClick={(e) => {
                    request(`/information_forms/${event.row.id}`, {
                      method: 'PUT',
                    }).then((response) => {
                      if (response.status === 200) {
                        message.success('刷新专票信息表成功')
                        const {
                          invoicings_manage: {searchParams},
                        } = that.props;
                        that.handleSearch(searchParams);
                      }
                    });
                  }}
                >
                </Button>
            </div>
          }else{
            return '无'
          }
        }
      },
      {
        name: '操作',
        width: 400,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          {
            find(that.permissions, {name: 'paper_invoicing'})  && (event.row.invoicing_status === 2||event.row.invoicing_status === -5) &&
              <Button
                type="primary"
                size="small"
                icon="table"
                onClick={(e) => {
                  request(`/invoices`, {
                    method: 'GET',
                    params: {
                      order_number: event.row.order_number
                    }
                  }).then((response) => {
                    if (response.status === 200) {
                      window.open(`${response.data.data.url}`);
                    }
                  });
                }}
              >查看
              </Button>
          }

          {
            (find(that.permissions, {name: 'paper_invoicing'}) && (event.row.invoicing_type === 2 || event.row.invoicing_type === 3 || event.row.invoicing_type === 4)) && event.row.invoicing_status === 2 &&
            <Button
              type="primary"
              size="small"
              icon="table"
              onClick={(e) => {
                this.setState({
                  invoicingData: [{
                    ...event.row
                  }],
                  editRecord: event.row,
                  printInvoicingModal: true
                })
              }}
            >打印
            </Button>
          }
          {
            (find(that.permissions, {name: 'paper_invoicing'}) && (event.row.invoicing_type !== 1) && (event.row.invoicing_type !== 6) && (event.row.invoicing_type !== 7)) && event.row.invoicing_status === 2 &&
            (moment(event.row.invoicing_date).format('MM')=== moment().format('MM')) &&
            <Button
              type="danger"
              size="small"
              className={'btn-gold'}
              icon="table"
              onClick={(e) => {
                confirm({
                  title: `确定作废"${event.row.buyer_name}"发票吗?`,
                  content: <div>操作不可逆，请谨慎操作！ </div>,
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered: true,
                  maskClosable: true,
                  onOk() {
                    request(`/paper_invoicings/${event.row.order_number}/void`, {
                      method: 'POST',
                    }).then((response) => {
                      if (response.status === 200) {
                        console.log('作废纸质发票')
                        message.success('作废发票成功')
                        const {
                          invoicings_manage: {searchParams},
                        } = that.props;
                        that.handleSearch(searchParams);
                      }
                    });
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });

              }}
            >作废
            </Button>
          }
          {
            find(that.permissions, {name: 'paper_invoicing'}) && (event.row.invoicing_status === 2) && (event.row.invoicing_type === 1||
              event.row.invoicing_type === 2||event.row.invoicing_type === 4||event.row.invoicing_type === 6||event.row.invoicing_type === 7)
            && (event.row.invoicing_flag === 1) &&
            <Button
              type="danger"

              size="small"
              icon="table"
              onClick={(e) => {
                confirm({
                  title: `确定冲红"${event.row.buyer_name}"发票吗?`,
                  content: <div>操作不可逆，请谨慎操作！ </div>,
                  okText: '确定',
                  okType: 'danger',

                  cancelText: '取消',
                  centered: true,
                  maskClosable: true,
                  onOk() {
                    request(`/invoicings/${event.row.order_number}/reverse`, {
                      method: 'POST',
                    }).then((response) => {
                      if (response.status === 200) {
                        console.log('冲红纸质发票')
                        message.success('冲红发票成功')
                        const {
                          invoicings_manage: {searchParams},
                        } = that.props;
                        that.handleSearch(searchParams);
                      }
                    });
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });

              }}
            >冲红
            </Button>
          }
          {
            (find(that.permissions, {name: 'paper_invoicing'})) &&
            <Button
              size="small"
              icon="reload"
              onClick={(e) => {
                request(`/invoices`, {
                  method: 'GET',
                  params: {
                    order_number: event.row.order_number
                  }
                }).then((response) => {
                  if (response.status === 200) {
                    message.success('刷新发票成功')
                    const {
                      invoicings_manage: {searchParams},
                    } = that.props;
                    that.handleSearch(searchParams);
                  }
                });
              }}
            >刷新状态
            </Button>
          }
          {
            (find(that.permissions, {name: 'paper_invoicing'})) && event.row.invoicing_type === 4 &&event.row.invoicing_type === 7 &&
            event.row.invoicing_status ===2 &&
            (moment(event.row.invoicing_date).format('MM')!== moment().format('MM')) &&
            <Button
              size="small"
              icon="table"
              type="danger"
              onClick={(e) => {
                this.setState({
                  editRecord: event.row,
                  formsModal: true
                })
              }}
            >申请红字专票信息表
            </Button>
          }


        </Fragment>,
      },
    ].map(c => ({...defaultColumnProperties, ...c}));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>发票管理</span>
      </div>
      <div className="table-page">
        <div className="table-info">
          <div className="table-info-item  animated fadeInLeft">
            <p>发票总数</p>
            <h4>{meta.total}</h4>
          </div>
         <div className="table-info-item" >
            <p  style={{color:'green'}}>已开票张数</p>
            <h4 style={{color:'green'}}>{summary.invoiced_count}</h4>
          </div>
          <div className="table-info-item" style={{color:'green'}}>
            <p style={{color:'green'}}>已开票金额</p>
            <h4 style={{color:'green'}}>{summary.invoiced_amount}</h4>
          </div>
          {/*  <div className="table-info-item  animated fadeInLeft">
            <p style={{ color: '#26b51a' }}>缴费总金额</p>
            <h4 style={{ color: '#26b51a' }}> {summary.total_amount}</h4>
          </div>
          <div className="table-info-item  animated fadeInLeft">
            <p style={{ color: '#0068c9' }}>已开票金额</p>
            <h4 style={{ color: '#0068c9' }}>{summary.invoiced_amount}</h4>
          </div>
          <div className="table-info-item  animated fadeInLeft">
            <p style={{ color: '#e00000' }}>未开票金额 </p>
            <h4 style={{ color: '#e00000' }}>{summary.uninvoiced_amount}</h4>
          </div> */}
          <div size="large" className="table-info-right-item  animated fadeInRight">
            {
              (find(that.permissions, {name: 'custom_invoicing'})) &&
              <Button
                type="primary"
                icon="table"
                onClick={(e) => {
                  this.setState({
                    invoicingModal: true
                  })
                }}
              >开发票
              </Button>
            }
           {
            find(that.permissions, { name: 'invoice_export' }) &&
            <Tooltip title={'请先查询一次再导出'}>
              <Button
                className={'btn-green'}
                type="primary"
                icon="export"
                onClick={this.handleExportinvoicings_manage}
                style={{marginLeft:'10px'}}
              >导出开票记录
              </Button>
            </Tooltip>
          }


          </div>
        </div>
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return {...data[i], _index: i};
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                if (!String(row)) {
                  return;
                }
                this.props.dispatch({
                  type: 'invoicings_manage/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{...searchParams}}
                      resetScrollY={() => {
                        console.log('resetScrollY');
                        const {
                          invoicings_manage: {scrollData},
                        } = this.props;
                        const table = document.querySelector('.react-grid-Canvas');
                        setTimeout(() => {
                          table.scrollTop = 0;
                          table.scrollLeft = scrollData.x;
                        }, 0);

                      }}
                      meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Drawer
        title={`${this.state.editRecord.account && this.state.editRecord.account.name} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={780}
        visible={this.state.infoModal}
      >
        <Detail meter_id={this.state.editRecord.account ? this.state.editRecord.account.meter_id : ''}
                meter_number={this.state.editRecord.account ? this.state.editRecord.account.meter_number : ''}
                id={this.state.editRecord.account ? this.state.editRecord.account.id : ''}></Detail>
      </Drawer>
      <Modal
        title={<BuildModalTitle visible={this.state.invoicingModal} modalClass="invoicingModal"
                                title={`开具发票`}/>}
        visible={this.state.invoicingModal}
        centered
        destroyOnClose

        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onOk={() => {
          this.Invoicing()
        }}
        className="invoicingModal"
        width={1100}
        onCancel={() => {
          this.setState({invoicingModal: false});
        }}

      >
        <PaperInvoicing editRecord={this.state.editRecord} wrappedComponentRef={(inst) => this.InvoicingForm = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.invoicingModal2} modalClass="invoicingModal2"
                                title={`查看“${this.state.editRecord.account ? this.state.editRecord.account.name : ''}” 发票`}/>}
        visible={this.state.invoicingModal2}
        centered
        destroyOnClose

        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        className="invoicingModal2"
        onCancel={() => {
          this.setState({invoicingModal2: false});
        }}
        footer={null}
      >
        <div>
          <div style={{width: '440px', margin: '50px auto'}}>
            {
              this.state.invoicingData.map((item, index) => {
                return <div key={index}
                            onClick={() => {
                              if (!item.url) {
                                message.warn('该发票正在开票中,请稍后重试...')
                              } else {
                                window.open(`${item.url}`);
                              }
                            }} style={{
                  width: '200px',
                  height: '60px',
                  lineHeight: '60px',
                  cursor: 'pointer',
                  margin: '10px',
                  display: 'inline-block',
                  textAlign: 'center',
                  border: '1px solid #ccc',
                  borderRadius: '5px',
                  background: index === 1 ? '#ff7400' : '#0060c4',
                  color: '#fff',
                  fontWeight: 'bold',
                  fontSize: '18px'
                }}>
                  {index === 1 ? '查看纸质发票' : '查看专用发票'}</div>
              })
            }

          </div>
        </div>

      </Modal>

      <Modal
        title={<BuildModalTitle visible={this.state.printInvoicingModal} modalClass="printInvoicingModal"
                                title={`打印“${this.state.editRecord.buyer_name ? this.state.editRecord.buyer_name : ''}” 发票`}/>}
        visible={this.state.printInvoicingModal}
        centered
        destroyOnClose

        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        className="printInvoicingModal"
        onCancel={() => {
          this.setState({printInvoicingModal: false});
        }}
        footer={null}
      >
        <div>
          <div style={{width: '440px', margin: '50px auto', textAlign: 'center'}}>
            {
              this.state.invoicingData.length === 1 && this.state.invoicingData.map((item, index) => {
                let aes = myencrypt(`01!${item.invoice_code}!${item.invoice_number}!${item.amount}`)
                let encrypt = new JSEncrypt();
                let PUBLIC_KEY = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClj0t1b+O5Cq06d0yp4qZHM3OhNSmoaArC6qAhehT/DB23F/CCUSFrQCjADhOvCq+xu4JcNGQ1kpjhKVNb642QPlSDJ04QM/+3mKcu/WKLDZ+3zQYvNY41pcjTyxtUT9ixaBx8OQQfOp+qiAYYBtE9T6WRLCrl1YN0drpDvFylyQIDAQAB';
                encrypt.setPublicKey('-----BEGIN PUBLIC KEY-----' + PUBLIC_KEY + '-----END PUBLIC KEY-----');
                let encrypted2 = encrypt.encrypt(aes);
                return <a key={index}
                          href={`webprint:0,91650402MABXHAWE5W!${encodeURIComponent(encrypted2)}!01`}
                          style={{
                            width: '200px',
                            height: '60px',
                            lineHeight: '60px',
                            cursor: 'pointer',
                            margin: '10px',
                            display: 'inline-block',
                            textAlign: 'center',
                            border: '1px solid #ccc',
                            borderRadius: '5px',
                            background: item.invoicing_type === 4 ? '#ff7400' : '#33b4ff',
                            color: '#fff',
                            fontWeight: 'bold',
                            fontSize: '18px'
                          }}>
                  点击打印发票</a>
              })
            }

          </div>
        </div>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.formsModal} modalClass="formsModal"
                                title={`"${this.state.editRecord.buyer_name}"申请红字专票信息表`}/>}
        destroyOnClose
        visible={this.state.formsModal}
        centered
        width={550}
        onOk={this.handleEdit}
        className="formsModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ formsModal: false, editRecord: {} });
        }}

      >
        <AddOrEditForm
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />

      </Modal>
    </div>;
  }
}

export default BasicList;
